package com.jdy.haoduoaiteacher.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;


public class VoicePlayClickListener implements View.OnClickListener {
  public static final String TAG = "VoicePlayClickListener";
  public static boolean isPlaying = false;
  public static final String PREFIX = "voice_";
  private AnimationDrawable voiceAnimation = null;
  private final BaseAdapter adapter;
  public static VoicePlayClickListener currentPlayListener = null;
  private MediaPlayer mediaPlayer = null;
  private final SpeakForYouItem mSFYI;
  private final ImageView mCoverImg;
  private final ImageView mErrorImg;
  private final Activity mActivity;
  private final ProgressBar mProgressBar;
  private final ImageView mUnreadImg;
  private boolean bTo = false;
  private LeUser mLeUser;

    public interface VoiceClickListener {
        public void onVoiceClicked();
    }

    public VoiceClickListener getVoiceClickListener() {
        return mVoiceClickListener;
    }

    public void setVoiceClickListener(VoiceClickListener mVoiceClickListener) {
        this.mVoiceClickListener = mVoiceClickListener;
    }

    VoiceClickListener mVoiceClickListener;

  public VoicePlayClickListener(SpeakForYouItem sfyi, BaseAdapter adapter,
                                ImageView errorImg, ImageView coverImg, Activity activity,
                                ProgressBar pb, ImageView unreadImg, boolean bTo, VoiceClickListener li) {
      mVoiceClickListener = li;
    this.bTo = bTo;
    this.mSFYI = sfyi;
    this.adapter = adapter;
    this.mErrorImg = errorImg;
    this.mCoverImg = coverImg;
    this.mActivity = activity;
    this.mProgressBar = pb;
    this.mUnreadImg = unreadImg;
    mLeUser = ((MyTeacherApp) activity.getApplication()).getUserTeacher();
    // downloadAudioFile();
  }

  private void downloadAudioFile() {
    new AsyncTask<String, Void, File>() {
      @Override
      protected File doInBackground(String... urls) {
        String urldisplay = urls[0];
        InputStream inputStream = null;
        OutputStream outputStream = null;

        File resultFile = new File(generateVoiceFilePath(urldisplay));
        if (resultFile.exists()) {
          mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
              // stuff that updates ui
              mProgressBar.setVisibility(View.GONE);
            }
          });

          return resultFile;
        } else {
          mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
              mProgressBar.setVisibility(View.VISIBLE);
            }
          });
        }

        try {
          URL url = new URL(urldisplay);
          HttpURLConnection urlConnection = (HttpURLConnection) url
              .openConnection();
          urlConnection.setRequestMethod("GET");
          // urlConnection.setDoOutput(true);
          urlConnection.connect();
          inputStream = urlConnection.getInputStream();
          outputStream = new FileOutputStream(resultFile);
          int read = 0;
          byte[] bytes = new byte[1024];
          while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
          }
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (inputStream != null) {
            try {
              inputStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (outputStream != null) {
            try {
              // outputStream.flush();
              outputStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return resultFile;
      }

      @Override
      protected void onPostExecute(File file) {
        String filePath = file.getAbsolutePath();
        if (!(new File(filePath).exists())) {
          return;
        }
      }
    }.execute(mSFYI.Src);
  }

  public void stopPlayVoice() {
    voiceAnimation.stop();
      if (bTo) {
          mCoverImg.setImageResource(R.drawable.chatto_voice_playing);
      } else {
          mCoverImg.setImageResource(R.drawable.chatfrom_voice_playing);
      }

    if (mediaPlayer != null) {
      try {
        mediaPlayer.stop();
        mediaPlayer.release();
      } catch (IllegalStateException e) {
        // TODO: handle exception
      }
    }
    isPlaying = false;
    adapter.notifyDataSetChanged();
  }

  public void playVoice() {
    try {
      new AsyncTask<String, Void, File>() {
        @Override
        protected File doInBackground(String... urls) {
          String urldisplay = urls[0];
          return null;
//          if (mSFYI.posterType != PosterType.Parent) {
//            // 在線
//            return null;
//          } else {
//
//          }
//          InputStream inputStream = null;
//
//          OutputStream outputStream = null;
//
//          File mFolder = new File(Environment.getExternalStorageDirectory()
//              .getAbsolutePath() + "/haoduoaiteacher/");
//          if (!mFolder.exists()) {
//            mFolder.mkdir();
//          }
//
//          File resultFile = new File(generateVoiceFilePath(urldisplay));
//
//          if (resultFile.exists()) {
//            mActivity.runOnUiThread(new Runnable() {
//              @Override
//              public void run() {
//                // stuff that updates ui
//                mProgressBar.setVisibility(View.GONE);
//              }
//            });
//
//            return resultFile;
//          } else {
//
//            mActivity.runOnUiThread(new Runnable() {
//              @Override
//              public void run() {
//                // stuff that updates ui
//                mProgressBar.setVisibility(View.VISIBLE);
//              }
//            });
//
//          }
//
//          try {
//            URL url = new URL(urldisplay);
//
//            HttpURLConnection urlConnection = (HttpURLConnection) url
//                .openConnection();
//
//            urlConnection.setRequestMethod("GET");
//            // urlConnection.setDoOutput(true);
//
//            urlConnection.connect();
//
//            inputStream = urlConnection.getInputStream();
//
//            outputStream = new FileOutputStream(resultFile);
//
//            int read = 0;
//
//            byte[] bytes = new byte[1024];
//
//            while ((read = inputStream.read(bytes)) != -1) {
//              outputStream.write(bytes, 0, read);
//            }
//
//          } catch (Exception e) {
//            e.printStackTrace();
//          } finally {
//            if (inputStream != null) {
//              try {
//                inputStream.close();
//              } catch (IOException e) {
//                e.printStackTrace();
//              }
//            }
//            if (outputStream != null) {
//              try {
//                // outputStream.flush();
//                outputStream.close();
//              } catch (IOException e) {
//                e.printStackTrace();
//              }
//            }
//          }
//          return resultFile;
        }

        @Override
        protected void onPostExecute(File file) {
          if (file == null) {
            mProgressBar.setVisibility(View.GONE);
            mUnreadImg.setVisibility(View.GONE);
            mSFYI.hasRead = 1;
            putReadStatus(mSFYI.id, 1);
            mediaPlayer = new MediaPlayer();
            try {
              mediaPlayer.setDataSource(mSFYI.Src);
              mediaPlayer.prepare();
              mediaPlayer
                      .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                          if (mediaPlayer != null) {
                            mediaPlayer.release();
                            mediaPlayer = null;
                          }
                          stopPlayVoice(); // stop animation
                        }

                      });
              isPlaying = true;
              currentPlayListener = VoicePlayClickListener.this;
              mediaPlayer.start();
              showAnimation();
            } catch (Exception e) {
            }
            return;
          }

          String filePath = file.getAbsolutePath();

          if (!(new File(filePath).exists()) && Tools.isNotEmpty(mSFYI.relativeAudioPath)) {
           // Toast.makeText(mActivity, "文件不存在!", Toast.LENGTH_SHORT).show();
            filePath = HttpUtils.HOST_RESOURCE + mSFYI.relativeAudioPath;
          } else if (Tools.isEmpty(mSFYI.relativeAudioPath) || !(new File(filePath).exists())) {
            return;
          }

          mProgressBar.setVisibility(View.GONE);
          mUnreadImg.setVisibility(View.GONE);
          mSFYI.hasRead = 1;
          putReadStatus(mSFYI.id, 1);
          mediaPlayer = new MediaPlayer();
          try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer
                .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                  @Override
                  public void onCompletion(MediaPlayer mp) {
                    if (mediaPlayer != null) {
                      mediaPlayer.release();
                      mediaPlayer = null;
                    }
                    stopPlayVoice(); // stop animation
                  }
                });

            isPlaying = true;
            currentPlayListener = VoicePlayClickListener.this;
            mediaPlayer.start();
            showAnimation();
          } catch (Exception e) {

          }
        }
      }.execute(mSFYI.Src);// URLEncoder.encode(mSFYI.Src,
                           // "utf-8").replace("%2F", "/")
    } catch (Exception e) {
      // TODO: handle exception
    }
  }

  @SuppressLint("ResourceType")
  private void showAnimation() {
    if (bTo) {
      mCoverImg.setImageResource(R.drawable.voice_to_icon);
    } else {
      mCoverImg.setImageResource(R.anim.voice_from_icon);
    }
    voiceAnimation = (AnimationDrawable) mCoverImg.getDrawable();
    voiceAnimation.start();
  }

  @Override
  public void onClick(View v) {
    if (isPlaying) {
      currentPlayListener.stopPlayVoice();
    }

    playVoice();


  }

  private void putReadStatus(final int id, final int audio_read) {
    new CustomAsyncTask(mActivity, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {

          if (mVoiceClickListener != null) {
              mVoiceClickListener.onVoiceClicked();
          }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("audio_read", audio_read);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/teacher/history/sound/" + id, param_,
            HttpUtils.TAG_PUT_REQUEST);
      }
    }).execute();
  }

  private String generateVoiceFilePath(String url) {
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String[] stringArray = url.split("/");
    String fileName = stringArray[stringArray.length - 1];
    path += "/haoduoaiteacher/" + PREFIX + fileName;
    return path;
  }

}
